import Taro, {Component} from "@tarojs/taro";
import { View, Image, Text } from "@tarojs/components";

import {inject, observer} from "@tarojs/mobx";
import {IStoreProps} from '../../store/Stores'
import { pageSize, subTime, navigateTo, articleType } from '../../utils/common'

import './index.scss'

interface IHomeProps extends IStoreProps {}

@inject("stores")
@observer
class DynamicIndex extends Component<IHomeProps>{
  constructor(props){
    super(props)
  }

  state = {
    pageIndex: 1,
    pageSize: pageSize,
    totalCount: 0,
    items: [] as any[]
  }

  componentWillMount(): void {
    this.getItems()
  }

  handelRouter = (url: string = '/pages/index/index'): void => {
    navigateTo(url)
  }

  getItems(): void {
    let { dynamicStore } = this.props.stores
    let { pageIndex, pageSize } = this.state
    dynamicStore.getArticleList({
      id: articleType.dynamic,
      pageIndex,
      pageSize,
      callback: res => {
        if (pageIndex === 1) {
          this.setState({totalCount: res.totalCount, items:res.items})
        }else {
          const { items } = this.state;
          items.push(...res.items || []);
          this.setState({totalCount: res.totalCount, items})
        }
      }
    })
  }

  onReachBottom(): void {
    let {totalCount, pageSize, pageIndex} = this.state
    const {loading} = this.props.stores.homeStore;
    if (totalCount > pageIndex * pageSize && !loading) {
      this.setState({
        pageIndex: pageIndex + 1
      }, () => {
        this.getItems()
      })
    }
  }

  render() {
    let { items }  = this.state
    let [firstItem, ...item2] = items

    return(
      <View className='dynamic-index'>
        {items.length>0&&
        <View className='content-20'>
           <View className='recommend' onClick={this.handelRouter.bind(this, '/pages/dynamic/detail?id='+firstItem.id)}>
              <Image src={firstItem.coverPhoto} className='img' />
              <Text className='title text-overflow'>{firstItem.artTitle}</Text>
           </View>
          {
            item2.length>0&&
           <View className='list-wrap'>
             {
                item2.map(item => {
                return(
                  <View className='item' onClick={this.handelRouter.bind(this, '/pages/dynamic/detail?id='+item.id)} key={item.id}>
                    <View className='l'>
                      <Text className='title'>{item.artTitle}</Text>
                      <Text className='date'>{subTime(item.creationTime)}</Text>
                    </View>
                    <Image src={item.coverPhoto} className='img' />
                  </View>
                )
               })
             }
           </View>
          }
          {item2.length<=0&&<View className='page-none-info'>暂无更多信息...</View>}
        </View>
        }
        {
          !items&&
          <View className='page-none-info'>暂无更多信息...</View>
        }
      </View>
    )
  }
}

export default DynamicIndex
